package com.github.gaojh.mvc.websocket;

import com.github.gaojh.ioc.IocUtil;
import com.github.gaojh.ioc.annotation.WebSocket;
import com.github.gaojh.ioc.bean.ClassInfo;
import com.github.gaojh.ioc.bean.ClassScanner;
import com.github.gaojh.ioc.bean.Initializer;
import com.github.gaojh.server.handler.WebSocketAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author gaojh
 * @since 2020/3/26
 */
@Slf4j
public class WebSocketInitializer implements Initializer {
    @Override
    public void init(ClassScanner classScanner) throws Exception {
        List<ClassInfo> list = classScanner.getClassByAnnotation(WebSocket.class);
        for (ClassInfo classInfo : list) {
            if (!WebSocketAdapter.class.isAssignableFrom(classInfo.getBeanClass())) {
                log.error("注册WebSocket处理器失败：{} 需要实现WebSocketAdapter接口，本次初始化忽略！", classInfo.getBeanName());
                return;
            }

            WebSocket webSocket = classInfo.getBeanClass().getAnnotation(WebSocket.class);
            WebSocketAdapter webSocketAdapter = (WebSocketAdapter) IocUtil.getBean(classInfo.getBeanClass());
            WebSocketContext.addWebSocketAdapter(webSocket.value(), webSocketAdapter);
            log.debug("注册WebSocket处理器：{}", classInfo.getBeanName());
        }
    }
}
